# encoding: utf-8
import os

from datetime import datetime
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import models
import base_def
import memcache_def

class BaseRequestHandler(webapp.RequestHandler):
	"""Base classs"""
	def __init__(self):
		self.list_settings = memcache_def.get_setting_memcache()
		self.settings = base_def.wgw_change_setting(self.list_settings)
		self.pages = memcache_def.get_page_memcache()

	def generate(self, template_name, template_values={}):
		links = memcache_def.get_link_memcache()
		values = {
			'path': self.request.path,
			'links': links,
			'list_settings': self.list_settings,
			'settings': self.settings,
			'pages': self.pages
		}
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values))

class root_base(BaseRequestHandler):
	def get(self):
		self.generate('root_base.html')

class addpost_root_base(BaseRequestHandler):
	def get(self):
		ar_id = self.request.get('id')
		categories = memcache_def.get_category_memcache()
		if ar_id:
			article = models.Article.get_by_id(int(ar_id))
			ar_ca_list = []
			for ar_ca in article.categories_keys:
				for category in categories:
					if category.key() == ar_ca:
						category.use = True
			values = {
				'article': article,
				'categories': categories
			}
		else:
			values = {
				'categories': categories
			}
		self.generate('addpost_root_base.html',values)
	def post(self):
		article_type = self.request.get('save_type')
		article_title = self.request.get('post_title')	#取得文章标题
		article_content = self.request.get('post_content')	#取得文章内容
		article_categorys = self.request.get_all('select_categories')	#取得文章分类的 list 对象
		#取得文章分类的 key 列表 以便存储到 Article 对象中
		category_keys = []
		for ar_cate in article_categorys:
			category_keys.append(db.Key(ar_cate))
		article_id = self.request.get('id_article_hidden')
		#取得文章分类的 key 列表 以便存储到 Article 对象中 END
		if article_id:
			article = models.Article.get_by_id(int(article_id))
			article.title = article_title
			article.content = article_content
			article.article_type = article_type
			article.categories_keys = category_keys
			article.put()
		else:
			article = models.Article(title=article_title, content=article_content, categories_keys=category_keys)
			article.month_year = datetime.strftime(datetime.now(),'%m_%Y')
			article.article_type = article_type
			article.put()
		memcache_def.update_cundang_memcache()
		memcache_def.update_article_atom_memcache()
		if article_type=='page':
			memcache_def.update_page_memcache()
		if article_id:
			self.redirect(self.request.uri)
		else:
			self.redirect(self.request.uri+'?id='+str(article.key().id()))

class managecomment_root_base(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		if bookmark_id:
			time_date_page = models.Comment.get_by_id(int(bookmark_id)).time_date
			comments = models.Comment.all().order('-time_date').filter('time_date <=',time_date_page).fetch(limit=self.settings['count_per_root']+1)
			pre_comments = models.Comment.all().order('time_date').filter('time_date >',time_date_page).fetch(limit=self.settings['count_per_root'])
		else:
			comments = models.Comment.all().order('-time_date').fetch(limit=self.settings['count_per_root']+1)
			pre_comments = None
		values_posts={
			'comments': comments[:self.settings['count_per_root']],
			'path': self.request.path
		}
		if len(comments) == self.settings['count_per_root']+1:
			values_page = {
				'next_page': comments[self.settings['count_per_root']]
			}
			values_posts.update(values_page)
		if (pre_comments) and (len(pre_comments)>0):
			values_pre_page = {
				'pre_page': pre_comments[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('managecomment_root_base.html', values_posts)
	def post(self):
		db.delete(db.Key(self.request.get('comment_key_hidden')))
		memcache_def.update_comment_memcache(self.settings['count_rec_comments'])
		self.redirect(self.request.uri)

class managepost_root_base(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		if bookmark_id:
			time_date_page = models.Article.get_by_id(int(bookmark_id)).time_date
			articles = models.Article.all().order('-time_date').filter('time_date <=',time_date_page).filter('article_type','article').fetch(limit=self.settings['count_per_root']+1)
			pre_articles = models.Article.all().order('time_date').filter('time_date >',time_date_page).filter('article_type','article').fetch(limit=self.settings['count_per_root'])
		else:
			articles = models.Article.all().order('-time_date').filter('article_type','article').fetch(limit=self.settings['count_per_root']+1)
			pre_articles = None
		values_posts={
			'articles': articles[:self.settings['count_per_root']],
			'path': self.request.path
		}
		if len(articles) == self.settings['count_per_root']+1:
			values_page = {
				'next_page': articles[self.settings['count_per_root']]
			}
			values_posts.update(values_page)
		if (pre_articles) and (len(pre_articles)>0):
			values_pre_page = {
				'pre_page': pre_articles[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('managepost_root_base.html', values_posts)
	def post(self):
		key_post = db.Key(self.request.get('key_post_hidden'))
		comments = models.Comment.all().filter('article',key_post)
		if comments:
			db.delete(comments)
		db.delete(key_post)
		memcache_def.update_cundang_memcache()
		self.redirect(self.request.uri)

class editcategory(BaseRequestHandler):
	def get(self):
		categories = memcache_def.get_category_memcache()
		value = {
			'categories': categories
		}
		self.generate('editcategory_root_base.html', value)
	def post(self):
		is_add = self.request.get('add_name_category_text')
		is_delete = self.request.get('delete_category_checkbox')
		key_category = self.request.get('key_category_hidden')
		if is_add:
			add_name_category = self.request.get('add_name_category_text')
			add_category = models.Category(name=add_name_category)
			add_category.put()
		elif is_delete:
			db.delete(db.Key(key_category))
		else:
			key_name = self.request.get('name_category_text')
			category = db.get(db.Key(key_category))
			category.name = key_name
			category.put()
		memcache_def.update_category_memcache()
		self.redirect(self.request.uri)

class managelink(BaseRequestHandler):
	def get(self):
		self.generate('managelink_root_base.html')
	def post(self):
		name_link = self.request.get('name_link')
		url_link = self.request.get('url_link')
		title_link = self.request.get('title_link')
		type_submit = self.request.get('type_submit')
		if type_submit == 'add':
			new_link = models.Link(name=name_link, url=url_link, title=title_link)
			new_link.put()
		elif type_submit == 'edit_del':
			key_link = self.request.get('key_link')
			is_delete = self.request.get('checkbox_delete')
			if is_delete == 'delete':
				db.delete(db.Key(key_link))
			else:
				edit_link = db.get(db.Key(key_link))
				edit_link.name = name_link
				edit_link.url = url_link
				edit_link.title = title_link
				edit_link.put()
		memcache_def.update_link_memcache()
		self.redirect(self.request.uri)

class upload_file_root(BaseRequestHandler):
	def get(self):
		values = {
		}
		self.generate(template_name='upload_file.html',template_values=values)
	def post(self):
		img = self.request.get('img')
		image = models.Image()
		image.content = db.Blob(img)
		image.put()
		values = {
			'image': image
		}
		self.generate(template_name='upload_file.html',template_values=values)

class deleteimage_root_base(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		if bookmark_id:
			key_page = models.Image.get_by_id(int(bookmark_id)).key()
			images = models.Image.all().order('-__key__').filter('__key__ <=',key_page).fetch(limit=self.settings['count_per_root']+1)
			pre_images = models.Image.all().order('__key__').filter('__key__ >',key_page).fetch(limit=self.settings['count_per_root'])
		else:
			images = models.Image.all().order('-__key__').fetch(limit=self.settings['count_per_root']+1)
			pre_images = None
		values_posts={
			'images': images[:self.settings['count_per_root']],
			'path': self.request.path
		}
		if len(images) == self.settings['count_per_root']+1:
			values_page = {
				'next_page': images[self.settings['count_per_page']]
			}
			values_posts.update(values_page)
		if (pre_images) and (len(pre_images)>0):
			values_pre_page = {
				'pre_page': pre_images[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('deleteimage_root_base.html',values_posts)
	def post(self):
		db.delete(db.Key(self.request.get('key_image_form')))
		self.redirect(self.request.uri)

class managedraft_root(BaseRequestHandler):
	def get(self):
		drafts = models.Article.all().filter('article_type','draft').order('time_date').fetch(1000)
		values = {
			'drafts': drafts
		}
		self.generate('managedraft_root_base.html', values)
	def post(self):
		key_post = db.Key(self.request.get('key_post_hidden'))
		db.delete(key_post)
		self.redirect(self.request.uri)

class managepage(BaseRequestHandler):
	def get(self):
		self.generate('managepage_root_base.html')
	def post(self):
		key_page = self.request.get('key_page')
		db.delete(db.Key(key_page))
		memcache_def.update_page_memcache()
		self.redirect(self.request.uri)

class setting(BaseRequestHandler):
	def get(self):
		self.generate('setting_root_base.html')
	def post(self):
		value_setting = self.request.get('value_setting')
		miaoshu_setting = self.request.get('miaoshu_setting')
		key_setting = self.request.get('key_setting')
		edit_setting = db.get(db.Key(key_setting))
		edit_setting.value = value_setting
		edit_setting.miaoshu = miaoshu_setting
		edit_setting.put()
		memcache_def.update_setting_memcache()
		self.redirect(self.request.uri)

class update_datastore(BaseRequestHandler):
	def get(self):
		article_key = self.request.get('b', None)
		if article_key is None:
			# 第一次修改
			article_key = models.Article.all().order('__key__').get().key()
		else:
			article_key = db.Key(article_key)
		articles = models.Article.all().order('__key__').filter('__key__ >=',article_key).fetch(2)
		article = articles[0]
		if len(articles) == 2:
			next_article = articles[1]
		else:
			next_article = None
		article.article_type = 'article'
		article.put()
		values = {
			'next_article': next_article
		}
		self.generate('update_datastore_root_base.html', values)

class error_base(BaseRequestHandler):
	def get(self,value=None):
		value = {'error': 'not found the page'}
		self.generate('error_base.html', value)

def main():
	application = webapp.WSGIApplication(
		[('/root.html$', root_base),
		('/addpost_root.html$', addpost_root_base),
		('/managecomment_root.html$', managecomment_root_base),
		('/managepost_root.html$', managepost_root_base),
		('/editcategory_root.html$', editcategory),
		('/deleteimage_root.html$', deleteimage_root_base),
		('/upload_file_root.html$', upload_file_root),
		#('/update_datastore_root.html$', update_datastore),
		('/managedraft_root.html$', managedraft_root),
		('/managelink_root.html$', managelink),
		('/setting_root.html$',setting),
		('/managepage_root.html$', managepage),
		('/(.*)', error_base)],
		debug=True)
	run_wsgi_app(application)

if __name__ == '__main__':
	main()
